package com.cn.zengzeng.spbzengzeng.singleton.dto2;

/**
 * 懒汉式加载  非线程安全
 * @Author: ZhangZengZeng
 * @Date: 2023/3/18 15:42
 */
public class SingletonDemo {

    private static volatile SingletonDemo singletonDemo = null ;
    private SingletonDemo(){
    }

    public static SingletonDemo getInstance(){
        try {
            Thread.sleep(5000);
        }catch(InterruptedException e) {
            throw new RuntimeException(e);
        }
        //双重校验锁  保证线程安全
        if(singletonDemo==null){
            synchronized(SingletonDemo.class){
                if(singletonDemo==null){
                    singletonDemo = new SingletonDemo();
                }
            }
        }
        return singletonDemo ;
    }

    public static void main (String[] args) {
        for(int i = 0;i < 10;i++) {
            new Thread(new Runnable() {
                @Override
                public void run () {
                    SingletonDemo instance = SingletonDemo.getInstance();
                    System.out.println("instance = " + instance);
                }
            }).start();
        }
    }
}
